package com.example.yichuangyun.ui.fragment;

import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentPhoneBinding;
import com.example.yichuangyun.dialog.CallDialog;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.dialog.TimePicker;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.business.CallRecordDataModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.ui.activity.call.SearchCallRecordActivity;
import com.example.yichuangyun.ui.adapter.CallRecordAdapter;
import com.example.yichuangyun.ui.adapter.LabelAdapter2;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.RequestUtils;
import com.example.yichuangyun.utils.sharedpreference.SPUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 电话
 */
public class PhoneFragment extends BaseFragment<FragmentPhoneBinding, BaseViewModel> implements LabelAdapter2.OnLabelItemListener {

    private CallRecordAdapter callRecordAdapter;
    private List<CallRecordDataModel.CallListModel> recordData = new ArrayList<>();
    private int page = 1;
    private LabelAdapter2 callDeviceAdapter;
    private LabelAdapter2 callTypeAdapter;
    private String callDevice;
    private String callType;
    private TimePicker timePicker;
    private boolean isStartTime;
    private String startTime;
    private String endTime;
    private CallDialog callDialog;
    /**
     * 输入的电话号码
     */
    private String number;

    /**
     * 拨打的电话号码
     */
    private String mTelNumber;
    private MyDialog myDialog;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void initData() {
        binding.includeSelect.recyclerViewCallDevice.setLayoutManager(new GridLayoutManager(mContext, 3));
        binding.includeSelect.recyclerViewCallType.setLayoutManager(new GridLayoutManager(mContext, 3));
        initDialog();
        initCallDialog();
        initSelectData();
        initTimePicker();
    }

    @Override
    public void lazyLoadData() {
        showLoadingDialog();
        getCallRecord(page);
    }

    private void initCallDialog() {
        callDialog = new CallDialog(getActivity()) {
            @Override
            public void clickNum(String num) {
                if (TextUtils.isEmpty(num)) {
                    binding.llTopContainer.setVisibility(View.VISIBLE);
                    binding.tvNum.setVisibility(View.GONE);
                    number = "";
                } else {
                    binding.llTopContainer.setVisibility(View.GONE);
                    binding.tvNum.setVisibility(View.VISIBLE);
                    number = num;
                    binding.tvNum.setText(num);
                    page = 1;
                }
                getCallRecord(page);
            }

            @Override
            public void callNum(String num) {
                RequestUtils.checkCallNum(mContext, num, null, 1, true);
            }
        };
    }

    /**
     * 通话记录
     */
    private void getCallRecord(int page) {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("parm", number);
            requestDate.put("telType", callDevice);
            requestDate.put("callType", callType);
            requestDate.put("trackTimeStart", startTime);
            requestDate.put("trackTimeEnd", endTime);
            requestDate.put("selectType", 1);
            requestDate.put("current", page);
            requestDate.put("size", Constant.pageSize);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getBusinessCallLog(requestBody), new MyObserver<HttpRespond<CallRecordDataModel>>() {
            @Override
            protected void onSuccess(HttpRespond<CallRecordDataModel> callRecordDataModelHttpRespond) {
                if (Constant.SUCCESS == callRecordDataModelHttpRespond.code) {
                    if (callRecordDataModelHttpRespond.data != null) {
                        if (callRecordDataModelHttpRespond.data.getRecords() != null) {
                            List<CallRecordDataModel.CallListModel> list = callRecordDataModelHttpRespond.data.getRecords();
                            if (list.size() == 0) {
                                binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                            }
                            if (page == 1) {
                                recordData = list;
                                callRecordAdapter.onRefresh(list);
                                binding.smartRefreshLayout.finishRefresh();
                            } else {
                                callRecordAdapter.addData(list);
                                binding.smartRefreshLayout.finishLoadMore();
                            }
                        }
                    }
                } else {
                    binding.smartRefreshLayout.finishRefresh();
                    binding.smartRefreshLayout.finishLoadMore();
                }
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                binding.smartRefreshLayout.finishRefresh();
                binding.smartRefreshLayout.finishLoadMore();
                dismissLoadingDialog();
            }
        });
    }

    @Override
    public void initCtrl() {
        callRecordAdapter = new CallRecordAdapter(mContext, recordData);
        binding.recyclerView.setAdapter(callRecordAdapter);
    }

    @Override
    public void initClick() {
        binding.ivSelect.setOnClickListener(v -> binding.drawerLayout.openDrawer(GravityCompat.END));
        binding.includeSelect.tvStartTime.setOnClickListener(v -> {
            isStartTime = true;
            timePicker.showPickerView();
        });
        binding.includeSelect.tvEndTime.setOnClickListener(v -> {
            isStartTime = false;
            timePicker.showPickerView();
        });
        binding.includeSelect.tvConfirm.setOnClickListener(v -> {
            binding.drawerLayout.closeDrawers();
            page = 1;
            binding.recyclerView.scrollToPosition(0);
            binding.smartRefreshLayout.autoRefresh();
        });
        binding.includeSelect.tvReset.setOnClickListener(v -> {
            callDeviceAdapter.resetData();
            callTypeAdapter.resetData();
            callDevice = null;
            callType = null;
            startTime = null;
            endTime = null;
            binding.includeSelect.tvStartTime.setText("");
            binding.includeSelect.tvEndTime.setText("");
        });
        binding.ivSearch.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                JumpIntent.jump(getActivity(), SearchCallRecordActivity.class);
            }
        });
        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getCallRecord(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getCallRecord(page);
            }
        });

        binding.tvNum.setOnClickListener(v -> callDialog.showDialog());

        callRecordAdapter.setOnCallListener(number -> {
            mTelNumber = number;
            RequestUtils.checkCallNum(mContext, mTelNumber, myDialog, 0, true);
        });
    }

    private void initSelectData() {
        List<LabelModel> callDeviceData = new ArrayList<>();
        callDeviceData.add(new LabelModel(mContext.getString(R.string.app_name), "1", false));
        callDeviceData.add(new LabelModel(mContext.getString(R.string.call_system), "2", false));
        callDeviceData.add(new LabelModel(mContext.getString(R.string.callback_outbound), "10", false));
        callDeviceAdapter = new LabelAdapter2(0, mContext, callDeviceData, this);
        binding.includeSelect.recyclerViewCallDevice.setAdapter(callDeviceAdapter);

        List<LabelModel> callTypeData = new ArrayList<>();
        callTypeData.add(new LabelModel(mContext.getString(R.string.outgoing_call), "2", false));
        callTypeData.add(new LabelModel(mContext.getString(R.string.incoming_call), "1", false));
        callTypeData.add(new LabelModel(mContext.getString(R.string.missed), "3", false));
        callTypeAdapter = new LabelAdapter2(1, mContext, callTypeData, this);
        binding.includeSelect.recyclerViewCallType.setAdapter(callTypeAdapter);
    }

    @Override
    public void onLabelItemClickListener(int flag, LabelModel model) {
        if (flag == 0) {
            callDevice = model.isSelect() ? model.getCode() : null;
        } else {
            callType = model.isSelect() ? model.getCode() : null;
        }
    }

    private void initTimePicker() {
        timePicker = new TimePicker(getActivity()) {
            @Override
            public void confirm(String date) {
                if (isStartTime) {
                    startTime = date + " 00:00:00";
                    binding.includeSelect.tvStartTime.setText(date);
                } else {
                    endTime = date + " 23:59:59";
                    binding.includeSelect.tvEndTime.setText(date);
                }
            }
        };
    }

    private void initDialog() {
        myDialog = new MyDialog(getActivity()) {
            @Override
            public void leftClick() {
                RequestUtils.callNum(mContext, mTelNumber);
            }

            @Override
            public void rightClick() {
                RequestUtils.callbackOutbound(mContext, mTelNumber, null, null);
            }
        };
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            boolean isShowed = SPUtil.getBoolean(Constant.isShowedKey, false);
            if (!isShowed) {
                MyDialog myDialog = new MyDialog(getActivity()) {
                    @Override
                    public void rightClick() {
                        SPUtil.put(Constant.isShowedKey, true);
                        showNumDialog();
                    }
                };
                myDialog.setCancelHide();
                myDialog.setCancel(false);
                myDialog.setText(mContext.getString(R.string.tips), mContext.getString(R.string.long_press_copy_num));
                myDialog.showDialog();
            } else {
                showNumDialog();
            }
        }
    }

    public void showNumDialog() {
        if (callDialog != null && SPUtil.getBoolean(Constant.isShowedKey, false)) {
            callDialog.showDialog();
        }
    }
}
